﻿using Game.NetWork.Packages;
using Game.NetWork;
using Engine;
using System;
using System.Text;
using System.Collections.Generic;
using static Game.MusketBlock;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices.ComTypes;
using System.Threading.Tasks;
using GameEntitySystem;
using TemplatesDatabase;

namespace Game.Server.EssentialCmd
{
    public class CmdPlayerTime : AbstractProcessCmd
    {
        public override string Cmd => "pltime";
        public override string Introduce => "/pltime v  -更改玩家游玩时间，v为数值";
        public override int AuthLevel => 100;
        public override DisplayType Display => DisplayType.All;

        public override void ProcessCmd()
        {
            if (GameManager.Project == null) return;
            if (m_messageDatas.Length == 2)
            {
                try
                {
                    SubsystemPlayers subsystemPlayers = GameManager.Project.FindSubsystem<SubsystemPlayers>();
                    List<PlayerData> playerDatas = new List<PlayerData>();
                    playerDatas.AddRange(subsystemPlayers.PlayersData);
                    foreach (var pla in playerDatas)
                    {
                        subsystemPlayers.RemovePlayerData(pla, true);
                    }
                    Console.WriteLine($"已成功清空玩家");
                    string worldPath = GameManager.Project.FindSubsystem<SubsystemGameInfo>().DirectoryName;
                    string path = Storage.CombinePaths(worldPath, "PlayerEntities");
                    if (Storage.DirectoryExists(path))
                    {
                        List<Guid> guids = new List<Guid>();
                        foreach (string guid in Storage.ListFileNames(path))
                        {
                            Guid guid2 = new Guid(guid.Split(new char[1] { '.' })[0]);
                            if (!guids.Contains(guid2))
                            {
                                guids.Add(guid2);
                            }
                        }
                        foreach (Guid guid in guids)
                        {
                            if (subsystemPlayers.CheckPlayerDataExists(guid, out string palyerPath))
                            {
                                ValuesDictionary dict = new ValuesDictionary();
                                using (Stream s = Storage.OpenFile(palyerPath, OpenFileMode.Read))
                                {
                                    byte[] d = new byte[s.Length];
                                    s.Read(d, 0, d.Length);
                                    dict.ApplyOverridesUseMessagePack(d);
                                }

                                ValuesDictionary data = dict.GetValue<ValuesDictionary>("Data");
                                double time = double.Parse(m_messageDatas[1]);
                                data.SetValue("FirstSpawnTime", time);
                                data.SetValue("LastSpawnTime", time);

                                using (Stream stream = Storage.OpenFile(palyerPath, OpenFileMode.Create))
                                {
                                    byte[] array = dict.ToMessagePack();
                                    stream.Write(array, 0, array.Length);
                                    stream.Flush();
                                }
                                using (Stream stream = Storage.OpenFile(palyerPath.Replace(".dat", ".json"), OpenFileMode.Create))
                                {
                                    StreamWriter streamWriter = new StreamWriter(stream);
                                    streamWriter.Write(dict.ToJsonText());
                                    streamWriter.Flush();
                                    streamWriter.Dispose();
                                }
                            }
                        }
                    }
                    subsystemPlayers.ServerGroups.Clear();
                    SendMessage(Cmd, "操作成功，请重新进入存档");
                    GameManager.SaveProject(true, false);
                    GameManager.DisposeProject();
                    CommonLib.Net.Stop();
                    ScreensManager.SwitchScreen("Play");
                }
                catch
                {
                    SendMessage(Cmd, "输入有误，请重试");
                }
            }
            else
            {
                SendMessage(Cmd, Introduce);
            }
        }
    }
}